﻿
Imports System.IO
Imports std
Imports xhtmlctrl

Namespace configNaming
    Namespace cssrequest
        Public Module cssrequest
            Public Const name As String = "cssrequest"
            Public Const crunch As String = "crunch"
        End Module
    End Namespace

    Namespace defaultValue
        Namespace cssrequest
            Public Module cssrequest
                Public Const crunch As Boolean = True
            End Module
        End Namespace
    End Namespace
End Namespace

Public Class cssrequest
    Inherits mergedStaticRequest

    'handle /css?a&b&c or /css?a.css&b.css&c.css
    'return the combine of a,b,c with filename a+b+c.css or a+b+c_c.css <crunched>
    'need to confirm there is not an existing static file has the name same as combine of some files
    'such as there should be a file named a_c.css, otherwise, it will be overwritten
    Public Const cssfilesuffix As String = ".css"
    Public Const crunchedfilesuffix As String = "_c.css"
    Private Shared configSection As String = Nothing
    Private Shared configCrunch As String = Nothing
    Public Shadows Const _pathidentity As String = "/cs/"

    Public Overrides Function pathidentity() As String
        Return _pathidentity
    End Function

    Protected Overrides Function suffix() As String
        Return cssfilesuffix
    End Function

    Protected Overrides Sub addresponseHeaders(ByVal context As httpContext, ByVal filename As String)
        MyBase.addresponseHeaders(context, filename)
        context.setcontentType(network.http.contentType.textcss)
    End Sub

    Private Shared Function needCrunch(ByVal context As httpContext) As Boolean
        debugassert(Not config Is Nothing, "config is nothing.")
        If config Is Nothing Then
            Return True
        Else
            Return config.parameter(configSection, configCrunch, _
                                    configNaming.defaultValue.cssrequest.crunch, context.filters())
        End If
    End Function

    Private Shared Function needCrunch() As Boolean
        Return needCrunch(httpServer2.currentContext())
    End Function

    Protected Overrides Function finalhandle(ByVal src As String) As String
        If Not needCrunch() Then
            Return src
        Else
            Dim dest As String = Nothing
            dest = barefilename(src) + crunchedfilesuffix

            Dim content As String = Nothing
            'trust the .net framework can get the right content encoding...
            Try
                content = File.ReadAllText(filefullpath(src))
            Catch ex As Exception
                raiseError("cannot read file " + filefullpath(src) + ", ignore request. " + ex.Message, _
                           errorHandle.errorType.warning)
                Return Nothing
            End Try
            csscrunch(content)
            Try
                File.WriteAllText(filefullpath(dest), content)
            Catch ex As Exception
                raiseError("cannot write to file " + filefullpath(dest) + ", ignore request. " + ex.Message, _
                           errorHandle.errorType.warning)
                Return Nothing
            End Try
            Return dest
        End If
    End Function

    Protected Overrides Function validfilename(ByVal filename As String) As Boolean
        Return MyBase.validfilename(filename) AndAlso _
               Not strendwith(filename, crunchedfilesuffix) AndAlso _
               Not strendwith(filename, strleft(crunchedfilesuffix, _
                                                strlen(crunchedfilesuffix) - strlen(cssfilesuffix)))
    End Function

    'do not hiden the generateMergedStaticfileLinkUrl, but give an alias
    Public Shared Function generateCssfileLinkUrl(ByVal ParamArray files() As String) As String
        Return generateMergedStaticfileLinkUrl(files)
    End Function

    Public Shared Shadows Function generateMergedStaticfileLinkUrl(ByVal ParamArray files() As String) As String
        Return mergedStaticRequest.generateMergedStaticfileLinkUrl(_pathidentity, files)
    End Function

    Public Sub New(Optional ByVal sectionNaming As String = configNaming.cssrequest.name, _
                   Optional ByVal crunchNaming As String = configNaming.cssrequest.crunch)
        copy(configSection, sectionNaming)
        copy(configCrunch, crunchNaming)
    End Sub

    Public Shared Function readcss(ByVal filename As String) As String
        'save cruched css in memory, avoid any unhandled exceptions, but use assert to confirm it can work.
        On Error Resume Next
        Dim fullname As String = Nothing
        fullname = staticrequest.filefullpath(filename)
        Dim rtn As String = Nothing
        rtn = File.ReadAllText(fullname)
        debugassert(Not rtn Is Nothing, "cannot read css " + fullname)
        If needCrunch() Then
            csscrunch(rtn)
            'assert(Not isemptystring(writercss), "writer.css is empty after csscrunch.")
        End If

        Return rtn
    End Function
End Class
